const requestHelper = require('../../utils/request');
const buildUrl = requestHelper.buildUrl || ((url) => url);
const { getUserLocation } = require('../../utils/location');

Page({
  data: {
    userInfo: {
      id: '',
      nickname: '',
      phone: '',
      avatarUrl: '',
      creditScore: 100,
      balance: 0,
      roles: [],
      isPhoneVerified: false,
      isRealNameVerified: false
    },
    userStats: {
      totalOrders: 0,
      completedOrders: 0
    },
    currentLocation: {
      latitude: '',
      longitude: '',
      campusText: ''
    },
    locating: false,

    notificationEnabled: true,
    cacheSize: '0KB',
    appVersion: '1.0.0',
    showLogoutModal: false,
    showClearCacheModal: false
  },

  onLoad() {
    this.loadUserProfile();
    this.getCacheSize();
    this.getAppVersion();
    this.loadLocation();
  },

  onShow() {
    this.loadUserProfile();
  },

  // 加载用户资料
  async loadUserProfile() {
    const app = getApp();
    const userId = app.globalData.userId;

    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    try {
      // 获取用户基本信息
      const userRes = await this.request({
        url: `/api/users/${userId}`,
        method: 'GET'
      });

      if (userRes.success) {
        this.setData({
          userInfo: {
            ...userRes.data,
            roles: this.getUserRoles(userRes.data)
          }
        });
      }

      // 获取用户统计数据
      const statsRes = await this.request({
        url: `/api/users/${userId}/stats`,
        method: 'GET'
      });

      if (statsRes.success) {
        this.setData({
          userStats: statsRes.data
        });
      }

      // 获取通知设置
      const notificationRes = await this.request({
        url: `/api/users/${userId}/notification-settings`,
        method: 'GET'
      });

      if (notificationRes.success) {
        this.setData({
          notificationEnabled: notificationRes.data.enabled || true
        });
      }

    } catch (error) {
      console.error('加载用户资料失败:', error);
      wx.showToast({ title: '数据加载失败', icon: 'none' });
    }
  },

  // 获取用户角色
  getUserRoles(userData) {
    const roles = [];
    if (userData.is_order_user) roles.push('order_user');
    if (userData.is_courier) roles.push('courier');
    return roles;
  },

  // 获取信用等级
  getCreditLevel(score) {
    if (score >= 90) return '信用极好';
    if (score >= 80) return '信用良好';
    if (score >= 70) return '信用一般';
    return '信用较差';
  },

  // 加载当前位置（使用全局定位工具 + 最近校园点）
  async loadLocation() {
    this.setData({ locating: true });
    try {
      const { latitude, longitude } = await getUserLocation();

      this.setData({
        currentLocation: {
          ...this.data.currentLocation,
          latitude,
          longitude,
          campusText: this.data.currentLocation.campusText
        }
      });

      // 调用后端获取最近的校园取件点，便于用户理解地点
      try {
        const resp = await this.request({
          url: `/api/orders/campus/nearest`,
          method: 'GET',
          data: {
            lat: latitude,
            lng: longitude,
            type: 'pickup_point'
          }
        });

        if (resp && resp.success && resp.data) {
          const loc = resp.data;
          const name = loc.name || '';
          const dist = loc.distance_m;
          const campusText = dist
            ? `${name}（约 ${dist} 米）`
            : name;

          this.setData({
            currentLocation: {
              latitude,
              longitude,
              campusText
            }
          });
        }
      } catch (e) {
        // 静默失败，仅保留经纬度
        console.warn('获取最近校园点失败:', e);
      }
    } catch (error) {
      console.error('加载定位失败:', error);
      wx.showToast({ title: '定位失败，请检查权限', icon: 'none' });
    } finally {
      this.setData({ locating: false });
    }
  },

  // 手动刷新定位
  refreshLocation() {
    this.loadLocation();
  },

  // 获取缓存大小
  getCacheSize() {
    wx.getStorageInfo({
      success: (res) => {
        const sizeKB = Math.round(res.currentSize);
        this.setData({
          cacheSize: sizeKB < 1024 ? `${sizeKB}KB` : `${(sizeKB / 1024).toFixed(1)}MB`
        });
      }
    });
  },

  // 获取应用版本
  getAppVersion() {
    const accountInfo = wx.getAccountInfoSync();
    this.setData({
      appVersion: accountInfo.miniProgram.version || '1.0.0'
    });
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 编辑资料
  editProfile() {
    wx.navigateTo({ url: '/pages/profile/editProfile' });
  },

  // 更换头像
  changeAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.uploadAvatar(tempFilePath);
      }
    });
  },

  // 上传头像
  async uploadAvatar(filePath) {
    wx.showLoading({ title: '上传中...' });

    try {
      const uploadRes = await this.uploadFile({
        url: '/api/users/avatar',
        filePath: filePath,
        name: 'avatar'
      });

      if (uploadRes.success) {
        this.setData({
          'userInfo.avatarUrl': uploadRes.data.avatarUrl
        });
        wx.showToast({ title: '头像更新成功' });
      } else {
        wx.showToast({ title: uploadRes.message || '上传失败', icon: 'none' });
      }
    } catch (error) {
      console.error('上传头像失败:', error);
      wx.showToast({ title: '上传失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  // 手机号验证
  goToPhoneVerify() {
    wx.navigateTo({ url: '/pages/profile/phoneVerify' });
  },

  // 修改密码
  changePassword() {
    wx.navigateTo({ url: '/pages/profile/changePassword' });
  },

  // 实名认证
  goToRealNameAuth() {
    wx.navigateTo({ url: '/pages/profile/realNameAuth' });
  },

  // 钱包管理
  goToWallet() {
    wx.navigateTo({ url: '/pages/profile/wallet' });
  },

  // 查看订单历史
  viewOrderHistory() {
    wx.navigateTo({ url: '/pages/orderList/orderList' });
  },

  // 查看已完成订单
  viewCompletedOrders() {
    wx.navigateTo({
      url: '/pages/orderList/orderList?filter=completed'
    });
  },

  // 查看信用详情
  viewCreditDetail() {
    wx.navigateTo({ url: '/pages/profile/creditDetail' });
  },

  // 代拿员绩效
  goToCourierPerformance() {
    wx.navigateTo({ url: '/pages/performance/performance' });
  },

  // 切换通知设置
  toggleNotification(e) {
    const enabled = e.detail.value;
    this.setData({ notificationEnabled: enabled });

    this.request({
      url: '/api/users/notification-settings',
      method: 'POST',
      data: { enabled }
    }).catch(error => {
      console.error('更新通知设置失败:', error);
    });
  },

  // 显示通知设置
  showNotificationSettings() {
    // 可以跳转到更详细的设置页面
    wx.showToast({ title: '通知设置', icon: 'none' });
  },

  // 隐私设置
  goToPrivacySettings() {
    wx.navigateTo({ url: '/pages/profile/privacySettings' });
  },

  // 清理缓存
  clearCache() {
    this.setData({ showClearCacheModal: true });
  },

  hideClearCacheModal() {
    this.setData({ showClearCacheModal: false });
  },

  // 确认清理缓存
  confirmClearCache() {
    wx.clearStorage({
      success: () => {
        this.setData({
          cacheSize: '0KB',
          showClearCacheModal: false
        });
        wx.showToast({ title: '缓存清理成功' });
      },
      fail: () => {
        wx.showToast({ title: '清理失败', icon: 'none' });
      }
    });
  },

  // 检查更新
  checkUpdate() {
    const updateManager = wx.getUpdateManager();

    updateManager.onCheckForUpdate((res) => {
      if (res.hasUpdate) {
        updateManager.onUpdateReady(() => {
          wx.showModal({
            title: '更新提示',
            content: '新版本已准备好，是否重启应用？',
            success: (res) => {
              if (res.confirm) {
                updateManager.applyUpdate();
              }
            }
          });
        });
      } else {
        wx.showToast({ title: '已是最新版本', icon: 'success' });
      }
    });
  },

  // 帮助中心
  showHelpCenter() {
    wx.navigateTo({ url: '/pages/profile/helpCenter' });
  },

  // 意见反馈
  showFeedback() {
    wx.navigateTo({ url: '/pages/profile/feedback' });
  },

  // 关于我们
  showAbout() {
    wx.navigateTo({ url: '/pages/profile/about' });
  },

  // 切换身份
  switchRole() {
    const app = getApp();
    const currentRole = app.globalData.userRole;
    const newRole = currentRole === 'order_user' ? 'courier' : 'order_user';

    app.switchRole(newRole);
    wx.showToast({
      title: `已切换到${newRole === 'order_user' ? '下单者' : '代拿员'}身份`
    });
  },

  // 显示退出确认
  showLogoutConfirm() {
    this.setData({ showLogoutModal: true });
  },

  hideLogoutModal() {
    this.setData({ showLogoutModal: false });
  },

  // 退出登录
  logout() {
    wx.clearStorageSync();
    getApp().globalData.userId = null;
    getApp().globalData.userRole = null;
    getApp().globalData.isLoggedIn = false;

    wx.reLaunch({ url: '/pages/login/login' });
  },

  // 网络请求封装
  request(options) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: buildUrl(options.url || ''),
        method: options.method || 'GET',
        data: options.data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 文件上传封装
  uploadFile(options) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: buildUrl(options.url || ''),
        filePath: options.filePath,
        name: options.name,
        header: {
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          const data = JSON.parse(res.data);
          resolve(data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }
});